#!/usr/bin/env python
# -*- coding: utf-8 -*-
#  category_content_app.py
#  description

#  Created by zhouzongli633 on 2020/8/19 4:11 下午.
#  Copyright ©Intellectus All rights reserved.
import json
import random

from django.db.models import Q

from Admin.models import Tag
from Baby.models import Users
from Common.decorators import check_token, check_param, method, check_body
from Common.logger import app_log
from Common.response import resp
from Common.span_tree import span_tree
from EducationContent.models import EducationCategory, CardAttributes, Source
from EducationContent.models import EducationFeeds, Hospital


@check_token()
@check_param(['user_id'])
@method(["GET"])
def categoryies_content_list(request):
    try:
        result = categoryies_content(request.GET.get('user_id'))
        return resp(0, result)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))

@method(["GET"])
def recommended_content_list(request):
    try:
        user = Users.objects.filter(id=request.GET.get('user_id')).first()
        language = 'EN'
        if not user:
            return resp(4001)
        data_list = []
        contents = EducationFeeds.objects.filter(hospital_id=user.hospital, is_delete=False).all()
        for content in contents:
            if random.randint(0, 99) % 10 != 0: continue
            content_dict = {
                "id": content.id,
                "category_id": content.category_id,
                "hospital_id": content.hospital_id,
                "title": content.title,
                "title_media": content.title_media_url if content.title_media_url else ""
            }
            if language == 'SP':
                content_dict['title'] = content.title_SP
                content_dict['title_media'] = content.title_media_url_SP if content.title_media_url_SP else ""
            data_list.append(content_dict)
        return resp(0, data_list)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_param(['user_id'])
@method(["GET"])
def bookmark_categoryies_content_list(request):
    try:
        result = categoryies_content(request.GET.get('user_id'), bookmark=True)
        return resp(0, result)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['user_id', 'content_id'])
def education_bookmark(request):
    try:
        post_param = json.loads(request.body)
        user = Users.objects.get(id=post_param['user_id'])
        content = EducationFeeds.objects.get(id=post_param['content_id'])
        if not user or not content:
            return resp(4001)
        bookmark_r = CardAttributes.objects.filter(user=user, feed=content).first()
        if not bookmark_r:
            bookmark_r = CardAttributes(
                feed=content,
                user=user,
                card_attribute='bookmark'
            )
            bookmark_r.save()

        ret = {
            'list': categoryies_content(post_param['user_id']),
            'tips': "bookmark success",
        }
        return resp(0, ret)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['user_id', 'content_id'])
def education_unbookmark(request):
    try:
        post_param = json.loads(request.body)
        user = Users.objects.get(id=post_param['user_id'])
        content = EducationFeeds.objects.get(id=post_param['content_id'])
        if not user or not content:
            return resp(4001)
        bookmark_r = CardAttributes.objects.filter(user=user, feed=content).first()
        if not bookmark_r:
            return resp(0, "this content hadn't bookmark yet")
        bookmark_r.delete()
        ret = {
            'list': categoryies_content(post_param['user_id']),
            'tips': "unbookmark success",
        }
        return resp(0, ret)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@check_token()
@check_body(['search_text', 'user_id'])
def contents_search(request):
    try:
        post_param = json.loads(request.body)
        user = Users.objects.get(id=post_param['user_id'])
        search_text = post_param['search_text']

        content = []
        records = EducationFeeds.objects.filter(
            Q(title__contains=search_text) or Q(summary_1__contains=search_text) or
            Q(summary_2__contains=search_text) or Q(page_info_SP__contains=search_text)
        ).all()
        for feed in records:
            ret = {
                "id": feed.id, "title": feed.title, "title_media_type": feed.title_media_type,
                "title_media_url": feed.title_media_url
            }

            if feed.title_media_url:
                ret['card_media'] = feed.title_media_url

            if CardAttributes.objects.filter(
                    feed=feed, user=user, card_attribute='bookmark').first():
                ret['bookmarked'] = True
            else:
                ret['bookmarked'] = False
            content.append(ret)
        return resp(0, content)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


def categoryies_content(user_id, bookmark=False):
    try:
        result = []
        user = Users.objects.get(id=user_id)
        if not user:
            return resp(4001)
        hospital = Hospital.objects.filter(hospital_name=user.hospital).first()

        categories = EducationCategory.objects.filter(hospital_id=hospital.id).all()
        origin_data = []
        for category in categories:
            category_j = {
                "cid": category.cid,
                "parent_id": category.parent_id,
                "title": category.title,
                "level": category.level,
            }
            contents = EducationFeeds.objects.filter(category_id=category.cid, hospital_id=hospital.id,
                                                     is_delete=False).all()
            content_list = []
            for content in contents:
                bookmarked = True if CardAttributes.objects.filter(user=user, feed=content).first() else False
                content_j = {
                    'id': content.id,
                    'title': content.title,
                    'title_media_type': content.title_media_type,
                    'title_media_url': content.title_media_url,
                    'bookmarked': bookmarked
                }
                if bookmark:
                    if bookmarked:
                        content_list.append(content_j)
                else:
                    content_list.append(content_j)
            category_j["content_list"] = content_list
            if bookmark:
                if len(content_list) > 0:
                    origin_data.append(category_j)
            else:
                origin_data.append(category_j)

        result = span_tree(origin_data)

        return resp(0, result)

    except Exception as e:
        app_log.exception(e)
        return []


@method(['POST'])
@check_body(['user_id', 'comment_text'])
def bookmarked(request):
    try:
        params = json.loads(request.body)
        user = Users.objects.get(id=params['user_id'])
        language = 'EN'
        if not user:
            return resp(4001)
        all_category = EducationCategory.objects.filter(hospital_id=user.hospital_id).all()
        data_list = []
        bookmarkeds = user.card_attributes.all()

        for single_data in all_category:
            single_data_dict = {}
            single_data_dict["id"] = single_data.id
            single_data_dict["cid"] = single_data.cid
            single_data_dict["parent_id"] = single_data.parent_id
            single_data_dict["title"] = single_data.title if language == 'EN' else single_data.title_SP
            single_data_dict["order_id"] = single_data.order_id
            single_data_dict["level"] = single_data.level
            single_data_dict["type"] = 0

            content_data = EducationFeeds.objects.filter(category_id=single_data.cid,
                                                         hospital_id=user.hospital_id,
                                                         is_delete=False
                                                         ).all()

            if content_data.exists():
                content_list = []
                for single_content in content_data:
                    content_dict = {}
                    related_content = []

                    data = single_content.educationFeeds_details_to_json()
                    content_dict["id"] = data["id"]
                    content_dict['type'] = 1
                    # content_dict["source"] = data["source"]
                    source = Source.objects.filter(id=int(single_content.source)).first()
                    content_dict["source"] = source.source_to_json() if source else {}
                    content_dict["category_id"] = data["category_id"]
                    content_dict["hospital_id"] = data["hospital_id"]
                    tags_ret = ""
                    tags = []
                    if data['tags']:
                        tags = data["tags"].split(',')
                    if tags:
                        for it in tags:
                            if it:
                                record = Tag.objects.filter(id=str(it)).first()
                                if record:
                                    if tags_ret == "":
                                        tags_ret = record.tag_title
                                    else:
                                        tags_ret = tags_ret + ',{}'.format(record.tag_title)

                    content_dict["tags"] = tags_ret
                    # content_dict["tags"] = data['tags']

                    content_dict["related_content"] = related_content
                    if language == 'EN':
                        content_dict["title"] = single_content.title
                        content_dict[
                            "title_media_type"] = single_content.title_media_type if single_content.title_media_url else ""
                    if language == 'SP':
                        content_dict["title"] = single_content.title_SP
                        content_dict[
                            "title_media_type"] = single_content.title_media_type if single_content.title_media_url_SP else ""

                    if single_content in bookmarkeds:
                        content_list.append(content_dict)

                single_data_dict['content_list'] = content_list
            else:
                single_data_dict['content_list'] = []

            if len(single_data_dict['content_list']) > 0:
                data_list.append(single_data_dict)
        return resp(0, data_list)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))


@method(['POST'])
@check_body(['user_id'])
def recommended(request, json=None):
    try:
        params = json.loads(request.body)
        user = Users.objects.get(id=params['user_id'])
        language = 'EN'
        if not user:
            return resp(4001)
        data_list = []
        contents = EducationFeeds.objects.filter(hospital_id=user.hospital_id, is_delete=False).all()
        for content in contents:
            if random.randint(0, 99) % 10 != 0: continue
            content_dict = {
                "id": content.id,
                "category_id": content.category_id,
                "hospital_id": content.hospital_id,
                "title": content.title,
                "title_media": content.title_media_url if content.title_media_url else ""
            }
            if language == 'SP':
                content_dict['title'] = content.title_SP
                content_dict['title_media'] = content.title_media_url_SP if content.title_media_url_SP else ""
            data_list.append(content_dict)
        return resp(0, data_list)
    except Exception as e:
        app_log.exception(e)
        return resp(-1, str(e))
